<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">{{ $t("login.form.title") }}</div>
    <div class="login-form-sub-title">{{ $t("login.form.subtitle") }}</div>
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <el-form
      ref="loginFormRef"
      :model="userInfo"
      class="login-form"
      :rules="rules"
    >
      <el-form-item
        prop="username"
        :rules="[
          {
            required: true,
            message: $t('login.form.userName.errMsg'),
            trigger: 'blur',
          },
        ]"
      >
        <el-input
          v-model="userInfo.username"
          :placeholder="$t('login.form.userName.placeholder')"
        >
          <template #prefix>
            <el-icon color="#409EFC" class="no-inherit">
              <User />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        prop="password"
        :rules="[
          {
            required: true,
            message: $t('login.form.password.errMsg'),
            trigger: 'blur',
          },
        ]"
      >
        <el-input
          v-model="userInfo.password"
          :placeholder="$t('login.form.password.placeholder')"
          type="password"
          autocomplete="off"
          clearable
          show-password
        >
          <template #prefix>
            <el-icon color="#409EFC" class="no-inherit">
              <Lock />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-space :size="16" direction="vertical">
          <div class="login-form-password-actions">
            <el-checkbox @change="setRememberPassword">
              {{ $t("login.form.rememberPassword") }}
            </el-checkbox>
            <el-link>{{ $t("login.form.forgetPassword") }}</el-link>
          </div>
          <el-button
            class="login-form-login-btn"
            type="primary"
            :loading="loading"
            @click="submitForm(loginFormRef)"
          >
            {{ $t("login.form.login") }}
          </el-button>
          <el-link class="login-form-register-btn">
            {{ $t("login.form.register") }}
          </el-link>
        </el-space>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";
import { useUserStore,useTabsStore } from "@/stores";
import { useI18n } from "vue-i18n";
import useLoading from "@/hooks/useLoading";
import {EnumLocalStorageKey} from "@/enums/localStorage"
const loginFormRef = ref<FormInstance>();
const userStore = useUserStore();
const tabsStore = useTabsStore()
const router = useRouter();
const { t } = useI18n();
const errorMessage = ref("");
const { loading, setLoading } = useLoading();
const userInfo = reactive({
  username: "",
  password: "",
});
const rules = reactive({});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      setLoading(true);
      try {
        await userStore.login(userInfo);
        const { redirect, ...othersQuery } = router.currentRoute.value.query;
        router.push({
          name: (redirect as string) || "root",
          query: {
            ...othersQuery,
          },
        });

        ElMessage.success(t("login.form.login.success"));
      } catch (err) {
        errorMessage.value = (err as Error).message;
      } finally {
        setLoading(false);
      }
    } else {
      return false;
    }
  });
};

const setRememberPassword = (value:boolean) => {
  if (value) {
    localStorage.setItem(EnumLocalStorageKey.UserPassword,userInfo.password)
  } else {
    localStorage.removeItem(EnumLocalStorageKey.UserPassword)
  }
};

onMounted(() => {
  // 监听enter事件（调用登录）
  document.onkeydown = (e: any) => {
    e = window.event || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      submitForm(loginFormRef.value);
    }
  };

  const localStoragePassword = localStorage.getItem(EnumLocalStorageKey.UserPassword)
  if(localStoragePassword){userInfo.password = localStoragePassword}

});
</script>

<style lang="scss" scoped>
.login-form {
  &-wrapper {
    width: 320px;
  }

  &-title {
    font-weight: 500;
    font-size: 24px;
    line-height: 32px;
  }

  &-sub-title {
    font-size: 16px;
    line-height: 24px;
  }

  &-error-msg {
    height: 32px;
    line-height: 32px;
  }

  &-password-actions {
    display: flex;
    width: 320px;
    justify-content: space-between;
  }

  &-login-btn {
    width: 320px;
  }
  &-register-btn {
    width: 320px;
  }
}
</style>
